package Joe.SiteManager.Web.Action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.apache.commons.io.FileUtils;

import Joe.SiteManager.Web.Common.PageBase;

public class UploadAction extends PageBase {

	private File upload;
	private String uploadFileName;
	private String uploadContentType;
	private String path = "";
	private String img;
	public String getImg() {
		return img;
	}

	public void setImg(String img) {
		this.img = img;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	
	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String execute() throws Exception {
		upload();
		return SUCCESS;
	}
	
	public void upload() throws IOException{
		if(upload != null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSS");
			Random r = new Random();
			String fileName = sdf.format(new Date()) + r.nextInt(100) + "." + uploadContentType.substring(uploadContentType.indexOf("/") + 1);
			String targetPath = this.context().getRealPath("/images");
			File file = new File(targetPath,fileName);
			if(!file.getParentFile().exists()){
				file.getParentFile().mkdirs();
			}
			FileUtils.copyFile(upload, file);
			path = "/" + fileName;
		}
	}
	
	@Override
	public void prepare() throws Exception {
		// TODO Auto-generated method stub
		
	}
}
